﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace csla4skeleton.DataAcess
{
    public class ExecuteSQLService
    {
        public static bool HasRowsExecuteQueryReader(string selectCommand)
        {
            try
            {
                bool result;
                SqlCommand command = GetSqlCommand(selectCommand);
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    result = reader.HasRows;
                    command.Connection.Close();
                    return result;
                }
                else
                {
                    command.Connection.Close();
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static SqlCommand GetSqlCommand(string selectCommand)
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Accounting"].ConnectionString);
            SqlCommand command = new SqlCommand(selectCommand, connection);
            return command;
        }

        public static int GetCurrentIdentityValue(string tableName)
        {
            try
            {
                int result = 0;
                string selectCommand = "SELECT IDENT_CURRENT('" + tableName + "') as CurrentIndentity";
                SqlCommand command = GetSqlCommand(selectCommand);
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    reader.Read();
                    result = Int32.Parse(reader["CurrentIndentity"].ToString());
                }

                command.Connection.Close();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static int GetTaiKhoanId(string maTaiKhoan)
        {
            try
            {
                int result = 0;
                string selectCommand = "SELECT Khoa FROM DM_TaiKhoan WHERE (Ma = '" + maTaiKhoan + "')";
                SqlCommand command = GetSqlCommand(selectCommand);
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    reader.Read();
                    result = Int32.Parse(reader["Khoa"].ToString());
                }

                command.Connection.Close();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
